package com.xteam.xnetworkdisk.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<String, Object> redisTemplate; // 主节点

//    @Autowired
//    private RedisTemplate<String, Object> readRedisTemplate; // 副节点

    // 写操作（主节点）
    public void write(String key,Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 读操作（主节点）
    public Object readTemplate(String key) {
        return redisTemplate.opsForValue().get(key);
    }

//    // 读操作（副节点）
//    public Object read(String key) {
//        return readRedisTemplate.opsForValue().get(key);
//    }

    public SetOperations<String, Object> getSetOperations() {
        return redisTemplate.opsForSet();
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public Boolean lock(String md5Value) {
        String lock = "lock:" + md5Value;
        Object o = readTemplate(lock);
        if (o != null) {
            return false;
        }
        write(lock, "locked");
        return true;
    }

    public void unlock(String md5Value) {
        String lock = "lock:" + md5Value;
        delete(lock);
    }

    public Set<String> keys(String key) {
         return redisTemplate.keys(key);
    }

    public Boolean lockFiveMinute(String redisKey) {
        String lock = "lock:" + redisKey;

        // 检查锁是否存在且未过期
        Object o = readTemplate(lock);
        if (o != null) {
            return false;
        }

        // 获取锁并设置过期时间为五分钟
        write(lock, "locked");
        redisTemplate.expire(lock, 5, TimeUnit.MINUTES); // 设置过期时间

        return true;

    }

    public Boolean acquireLock(String lockKey, long timeout) {
        String lock = "lock:" + lockKey;
        Boolean success = redisTemplate.opsForValue().setIfAbsent(lock, "locked", timeout, TimeUnit.MILLISECONDS);
        return success != null && success;
    }

    public void releaseLock(String lockKey) {
        redisTemplate.delete(lockKey);
    }

}
